package com.gj.demojuc.chap02;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写不可并发、读读可并发、写写不可并发
 */

class MyCache{
    private static HashMap<String,String> hashMap = new HashMap<>();

    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public void put(String key,String value){
        reentrantReadWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写入");
            Thread.sleep(300);
            hashMap.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
    }

    public void get(String key){
        reentrantReadWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读出");
            Thread.sleep(300);
            String value = hashMap.get(key);
            System.out.println(Thread.currentThread().getName() + "读出成功" + value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            reentrantReadWriteLock.readLock().unlock();
        }
    }
}

public class ReentrantReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.put(num,num);
            }).start();
        }

        for (int i = 0; i < 5; i++) {
            String num = String.valueOf(i);
            new Thread(()->{
                myCache.get(num);
            }).start();
        }
    }
}
